package com.wlps.config;

import com.wlps.entity.SysPermission;
import com.wlps.entity.SysUser;
import com.wlps.service.ISysPermissionService;
import com.wlps.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class CustomerUserDetailsService implements UserDetailsService {
    //注入UserService
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysPermissionService permissionService;
    //此处需要注入PasswordEncoder 不然会报错
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//1.根据用户username查询数据库是否有用户
        SysUser user = userService.getUserByUserName(username);
        if (null == user) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
//3.查询用户权限，设置到SysUser 的 authorities 中
        List<SysPermission> permissions = permissionService.selectPermissionByUserId(user.getId());
//4.获取code字段
        List<String> collect = permissions.stream().filter(item -> item !=
                null).map(item -> item.getCode()).collect(Collectors.toList());
//5.转成数组
        String[] codes = collect.toArray(new String[collect.size()]);
//6.把codes转成List<GrantedAuthority>

        List<GrantedAuthority> authorityList =
                AuthorityUtils.createAuthorityList(codes);
//7.设置权限
        user.setAuthorities(authorityList);
//8.设置用户所有菜单
        user.setPermissionList(permissions);
        return user;
    }

}

